package cisdi.mes.sm.rm.web;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cisdi.mes.sm.rm.service.BaseServ;
import cisdi.mes.sm.util.serviceImpl.FilterGroup;
import cisdi.mes.sm.util.serviceImpl.FilterTranslator;

@Controller
@RequestMapping("rm")
public class BaseController {

	@Resource(name="baseServImpl")
	private BaseServ baseServ;
	
	@RequestMapping("gridEdit")
	@ResponseBody
	public Map<String, Object> saveData(HttpServletRequest request,
			@RequestParam("domain") String domain) {
		String info = request.getParameter(domain);
		String className = "cisdi.mes.sm.rm.domain."+domain;
		Map<String, Object> serverInfo = new HashMap<String, Object>();

		try {
			ObjectMapper objectMapper = new ObjectMapper();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			objectMapper.setDateFormat(dateFormat);
			Class<?> clazz = Class.forName(className);
			Object daEntity = objectMapper.readValue(info,clazz);
			baseServ.save(daEntity);
			serverInfo.put("success", true);
			serverInfo.put("message", "修改成功！");
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			serverInfo.put("success", false);
			serverInfo.put("message", e.getMessage());
		}
		return serverInfo;
	}
	@RequestMapping("gridAdd")
	@ResponseBody
	public Map<String, Object> addData(HttpServletRequest request,
			@RequestParam("domain") String domain) {
		String info = request.getParameter(domain);
		String className = "cisdi.mes.sm.rm.domain."+domain;
		Map<String, Object> serverInfo = new HashMap<String, Object>();

		try {
			ObjectMapper objectMapper = new ObjectMapper();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			objectMapper.setDateFormat(dateFormat);
			Class<?> clazz = Class.forName(className);
			Object daEntity = objectMapper.readValue(info,clazz);
			baseServ.add(daEntity);
			serverInfo.put("success", true);
			serverInfo.put("message", "添加成功！");
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
			serverInfo.put("success", false);
			serverInfo.put("message", e.getMessage());
		}
		return serverInfo;
	}
	
	@RequestMapping("gridDelete")
	@ResponseBody
	public Map<String, Object> deleteData(HttpServletRequest request,
			@RequestParam("domain") String domain, @RequestParam("ids") String ids) {
		
		Map<String, Object> serverInfo = new HashMap<String, Object>();

		try {
			baseServ.delete("cisdi.mes.sm.rm.domain."+domain, ids.split(","));
			serverInfo.put("success", true);
			serverInfo.put("message", "删除成功！");
		} catch (Exception e) {
			e.printStackTrace();
			serverInfo.put("success", false);
			serverInfo.put("message", e.getMessage());
		}
		return serverInfo;
	}
	
	@RequestMapping("deleteRows")
	@ResponseBody
	public Map<String, Object> deleteRow(HttpServletRequest request,
			@RequestParam("domain") String domain, @RequestParam("rows") String rows) {
		
		String[] infos = new String[Integer.valueOf(rows)];
		for(int i=0;i<infos.length;i++){
			infos[i] = request.getParameter(String.valueOf(i));
		}
		String className = "cisdi.mes.sm.rm.domain."+domain;
		// 2定义输出
		Map<String, Object> serverInfo = new HashMap<String, Object>();

		try {
			// 3数据转换
			ObjectMapper objectMapper = new ObjectMapper();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			objectMapper.setDateFormat(dateFormat);
			Object[] daEntitys = new Object[infos.length];
			for(int i=0;i<daEntitys.length;i++){
				daEntitys[i] = objectMapper.readValue(infos[i],Class.forName(className));
			}
			baseServ.delete(daEntitys);
			serverInfo.put("success", true);
			serverInfo.put("message", "上传成功！");
		} catch (Exception e) {
			e.printStackTrace();
			serverInfo.put("success", false);
			serverInfo.put("message", e.getMessage());
		}
		return serverInfo;
	}
	
	@RequestMapping("filterQuery")
	@ResponseBody
	public Map<String, Object> queryDA(HttpServletRequest request,
			@RequestParam("domain") String domain) {
		 
		Map<String, Object> daGrid = new HashMap<String, Object>();

		String rules = request.getParameter("rules");
		String sortBy = request.getParameter("sortBy");
		String sortDir = request.getParameter("sortDir");
		String startStr = request.getParameter("start");
		String limitStr = request.getParameter("limit");
		
		int start = startStr!=null?Integer.parseInt(startStr):0;
		int limit = limitStr!=null?Integer.parseInt(limitStr):0;
		
		String queryString = "FROM " + domain;
		if (rules == null) {
			// 处理没有rules的情况
			if (sortBy != null && sortDir != null) {
				queryString += " ORDER BY " + sortBy + " "+ sortDir;
			}
			// 判断是否带有分页信息
			if (limit > 0) {
				daGrid = baseServ.query(queryString, start, limit);
			} else {
				daGrid = baseServ.query(queryString);
			}

		} else if (rules != null) {
			// 处理带有rules的情况
			ObjectMapper objectMapper = new ObjectMapper();
			FilterGroup group;
			try {
				group = objectMapper.readValue(rules, FilterGroup.class);
				FilterTranslator filterTranslator = new FilterTranslator(group);
				filterTranslator.translate();
				rules = filterTranslator.getCommandText();
				queryString = queryString + " WHERE " + rules;
				if (sortBy != null ) {
					if(sortDir == null){
						sortDir = "asc";
					}
					queryString = queryString + " ORDER BY " + sortBy + " "	+ sortDir;
				}
				String[] paramNames = filterTranslator.getParamNames();
				Object[] values = filterTranslator.getValues();
				// 判断是否带有分页信息
				if (limit > 0) {
					daGrid = baseServ.query(queryString, paramNames, values, start, limit);
				} else {
					daGrid = baseServ.query(queryString, paramNames, values);
				}
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println(queryString);
		return daGrid;
	}
}
